// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Card, Form, Input, Button, message, Select } from 'antd';

// 3. 图标库
import { SaveOutlined, ArrowLeftOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 工具库
import { useParams, history } from '@umijs/max';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIConversation, AIConversationRequest } from '@/services/generated';

const { Option } = Select;

const ConversationEdit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [models, setModels] = useState<any[]>([]);
  const [roles, setRoles] = useState<any[]>([]);
  const isEdit = !!id;

  // 状态选项
  const statusOptions = [
    { value: 'active', label: '活跃' },
    { value: 'archived', label: '已归档' },
    { value: 'deleted', label: '已删除' },
  ];

  // 获取AI模型和角色列表
  useEffect(() => {
    const fetchData = async () => {
      try {
        await autoLoginInDev();
        const [modelsRes, rolesRes] = await Promise.all([
          apiClients.aiChat.aiChatModelsList({}),
          apiClients.aiChat.aiChatRolesList({})
        ]);
        setModels(modelsRes.data?.items || []);
        setRoles(rolesRes.data?.items || []);
      } catch (error) {
        message.error('获取基础数据失败');
      }
    };
    fetchData();
  }, []);

  // 获取对话详情（编辑模式）
  useEffect(() => {
    if (isEdit && id) {
      const fetchConversation = async () => {
        try {
          await autoLoginInDev();
          const response = await apiClients.aiChat.aiChatConversationsRetrieve({ id });
          form.setFieldsValue({
            ...response.data,
          });
        } catch (error) {
          message.error('获取对话数据失败');
        }
      };
      fetchConversation();
    }
  }, [id, isEdit, form]);

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      const formData: AIConversationRequest = {
        ...values,
      };

      if (isEdit) {
        await apiClients.aiChat.aiChatConversationsUpdate({ 
          id: id!, 
          aIConversationRequest: formData 
        });
        message.success('更新成功');
      } else {
        await apiClients.aiChat.aiChatConversationsCreate({ 
          aIConversationRequest: formData 
        });
        message.success('创建成功');
      }

      // 跳转到列表页
      history.push('/ai-chat/conversations');
    } catch (error) {
      message.error(isEdit ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer
      header={{
        title: isEdit ? '编辑对话' : '新建对话',
        subTitle: isEdit ? `编辑对话 #${id}` : '创建新的对话会话',
      }}
    >
      <Card>
        <Form<AIConversationRequest>
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            status: 'active',
          }}
        >
          <Form.Item 
            name="title" 
            label="对话标题" 
            rules={[{ required: true, message: '请输入对话标题' }]}
          >
            <Input 
              placeholder="请输入对话标题，如：编程问题讨论、文案创作等" 
              maxLength={200}
              showCount
            />
          </Form.Item>

          <Form.Item 
            name="ai_model" 
            label="AI模型" 
            tooltip="选择用于此对话的AI模型"
          >
            <Select 
              placeholder="请选择AI模型（可选）"
              allowClear
            >
              {models.map(model => (
                <Option key={model.id} value={model.id}>
                  {model.name} ({model.model_code})
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item 
            name="ai_role" 
            label="AI角色" 
            tooltip="选择AI在此对话中扮演的角色"
          >
            <Select 
              placeholder="请选择AI角色（可选）"
              allowClear
            >
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.name} ({role.category})
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item 
            name="status" 
            label="状态" 
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择对话状态">
              {statusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              icon={<SaveOutlined />}
              style={{ marginRight: 8 }}
            >
              {isEdit ? '更新' : '创建'}
            </Button>
            <Button 
              icon={<ArrowLeftOutlined />}
              href="/ai-chat/conversations"
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default ConversationEdit;